<template>
	<view class="body">
		<scroll-view scroll-y="true" :scroll-top="scrollTop" @scrolltolower="loadMore" @scrolltoupper="refresh"
			scroll-with-animation="true" class="scroll-view">
			<!-- <view v-if="this.timeFrame == 1" class="dateText" @click="showCalendar()">
			{{$u.timeFormat(parentData.endTime, 'mm月dd日')}}
		</view>
		<view v-if="this.timeFrame != 1" class="dateText" @click="showCalendar()">
			{{$u.timeFormat(parentData.startTime, 'yyyy年mm月dd日')}}-{{$u.timeFormat(parentData.endTime, 'yyyy年mm月dd日')}}
		</view> -->
			<!-- <u-calendar v-model="showcalendar" :mode="mode" @change="Calendarchange"></u-calendar> -->
			<lechart :parentData='parentData' :setFuTime='setTime' :gettongji='gettongji'></lechart>
			<view style="background-color: #f2f2f2;padding: 0 30rpx 30rpx">
				<view class="title">
					数据统计
				</view>
				<view class="info">
					<view class="container">
						<view class="list">
							<view class="time">
								<view class="yuan lv" style="background-color: #3e88fd;"></view>
								收缩压
								<text style="margin-left: auto; font-size: 12px;">正常：{{alarm.BP.downDbp}} -
									{{alarm.BP.upDbp}}</text>
							</view>
							<view class="data">
								{{interval.Dbp.minMinValue}} - {{interval.Dbp.maxMaxValue}}<text>mmHg</text>
							</view>
						</view>
						<view class="list">
							<view class="time">
								<view class="yuan lv" style="background-color: #13cc7b;"></view>
								舒张压
								<text style="margin-left: auto; font-size: 12px;">正常：{{alarm.BP.downSbp}} -
									{{alarm.BP.upSbp}}</text>
							</view>
							<view class="data">
								{{interval.Sbp.minMinValue}} - {{interval.Sbp.maxMaxValue}}<text>mmHg</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="background-color: #f2f2f2;padding: 0 30rpx 30rpx">
				<view class="title">
					历史数据
				</view>
				<view class="info">
					<view class="container">
						<!-- 下拉刷新容器 -->
						<!-- 刷新状态提示 -->
						<view v-if="refreshing" class="refreshing">正在刷新...</view>
						<!-- 列表项 -->
						<view class="list" v-if='items.length > 0' v-for="(item, index) in items" :key="index">
							<view class="time">
								<image :src="$IMAGE_BASE_URL + '/img/new/xueya.png'"
									style="width: 30rpx; height: 30rpx;margin:0rpx 10rpx; float: left;"></image>
								血压
								<text
									style="margin-left: auto; font-size: 12px;">{{$u.timeFormat(item[0].time*1, 'mm-dd hh:MM:ss')}}</text>
							</view>
							<view class="data2">
								{{item[1].value}}/{{item[0].value}}<text>mmHg</text>
							</view>
							<view class="state2 red"
								v-if="item[1].value*1 > alarm.BP.upSbp*1 || item[0].value*1 >alarm.BP.upDbp*1">偏高</view>
							<view class="state2 red"
								v-else-if="item[1].value*1 < alarm.BP.downSbp*1 || item[0].value*1 <alarm.BP.downDbp*1">
								偏低</view>
							<view class="state2 lv" v-else>正常</view>
						</view>
						<!-- 加载状态提示 -->
						<view v-if="loading" class="loading">加载中...</view>
						<!-- 无更多数据提示 -->
						<view v-if="noMoreData" class="no-more-data">没有更多数据</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	// 条件编译引入小程序专用代码
	import lechart from "../chart/index.vue";
	import * as echarts from '../components/echarts.esm.min.js'
	import {
		getStatistics,
		historyPropert
	} from "../../../api/device/index.js";
	import {
		getCurrentPage
	} from '@/core/app'
	import StorageUtils from "../../../utils/StorageUtils";
	export default {
		components: {
			lechart,
		},
		data() {
			return {
				iotDeviceId: '',
				mode: 'date',
				opts: {},
				alarm: JSON.parse(StorageUtils.get('ALARM')),
				parentData: {
					identifier: 'Sbp,Dbp',
					name: '收缩压,舒张压',
					color: ["#3e88fd", "#13cc7b"]
				},
				interval: {
					Sbp: {
						minMinValue: 0,
						maxMaxValue: 0
					},
					Dbp: {
						minMinValue: 0,
						maxMaxValue: 0
					},
				},
				timeFrame: 'day7',
				items: [], // 列表数据
				refreshing: false, // 是否正在刷新
				loading: false, // 是否正在加载更多
				noMoreData: false, // 是否没有更多数据
				page: 0, // 当前页码
				scrollTop: 0, // 滚动条位置，用于重置滚动位置到顶部
			};
		},

		onReady() {
			this.iotDeviceId = getCurrentPage().query.iotDeviceId;
			// this.gethistoryPropert(this.iotDeviceId);
		},
		onLoad() {
			// this.loadData(); // 页面加载时获取初始数据
		},
		mounted() {

		},
		methods: {
			//子传入的参数
			gettongji(res) {
				// 1. 收集所有数据的maxValue和minValue
				const typeValues = {};
				let interval = this.interval;
				// 遍历外层数组
				res.forEach(innerArray => {
					// 遍历内层数组的每个对象
					innerArray.forEach(item => {
						const {
							dataType,
							maxValue,
							minValue
						} = item;
						// 转换为数字类型
						const max = Number(maxValue);
						const min = Number(minValue);
			
						// 如果该类型尚未初始化，创建初始结构
						if (!typeValues[dataType]) {
							typeValues[dataType] = {
								maxValues: [],
								minValues: []
							};
						}
						// 收集最大值和最小值
						typeValues[dataType].maxValues.push(max);
						typeValues[dataType].minValues.push(min);
					});
				});
			
				// 2. 计算每个类型的maxMaxValue和minMinValue，并更新到interval
				Object.keys(interval).forEach(type => {
					if (typeValues[type]) {
						// 有对应数据：计算实际最大/最小值
						interval[type].maxMaxValue = Math.max(...typeValues[type].maxValues);
						interval[type].minMinValue = Math.min(...typeValues[type].minValues);
					} else {
						// 无对应数据：强制设为0（覆盖任何初始值）
						interval[type].maxMaxValue = 0;
						interval[type].minMinValue = 0;
					}
				});
			},
			setTime(startTime, endTime, isMonthly, timeFrame) {
				this.startTime = startTime
				this.endTime = endTime
				this.isMonthly = isMonthly
				this.timeFrame = timeFrame
				this.loadData(startTime, endTime, true);
				// this.gettongji();
			},
			loadData(startTime, endTime, refresh = false) {
				let deviceId = getCurrentPage().query.iotDeviceId
				if (refresh) {
					this.noMoreData = false
				}
				if (this.refreshing || this.loading || this.noMoreData) return;
				let isRefresh = refresh;
				if (refresh) {
					this.refreshing = true;
					this.page = 1; // 刷新时重置页码为1
					this.items = []; // 清空列表数据
				} else {
					this.loading = true;
					this.page += 1; // 加载更多时页码加1
				}
				historyPropert({
					deviceId,
					startTime: startTime ? startTime : this.startTime,
					endTime: endTime ? endTime : this.endTime,
					current: this.page,
					size: 20,
					identifier: this.parentData.identifier
				}).then(res => {
					// res = res.obj
					let data = []
					data = res.obj.records.reduce((acc, curr) => {
						const existingGroup = acc.find(group => group[0].time === curr.time);
						if (existingGroup) {
							// 如果已存在组，则向该组添加新对象
							if (curr.key === 'Dbp' || curr.key === 'Sbp')
								existingGroup.push({
									key: curr.key,
									value: curr.value
								});
						} else {
							// 如果不存在组，则创建一个新组并初始化
							if (curr.key === 'Dbp' || curr.key === 'Sbp')
								acc.push([{
									time: curr.time,
									key: curr.key,
									value: curr.value
								}]);
						}
						return acc;
					}, []);
					if (data) {
						if (isRefresh) {
							this.items = data;
						} else {
							this.items = [...this.items, ...data];
						}
					}
					if (this.page >= res.obj.pages) {
						this.noMoreData = true;
					}
					if (isRefresh) {
						this.refreshing = false;
						this.scrollTop = 0; // 刷新成功后重置滚动位置到顶部（如果需要）
					} else {
						this.loading = false;
					}
				}).catch(error => {
					if (isRefresh) {
						this.refreshing = false;
					} else {
						this.loading = false;
					}
					uni.showToast({
						title: '加载失败',
						icon: 'none',
					});
				});
			},
			// 下拉刷新
			refresh() {
				// this.loadData(true);
			},
			// 上拉加载更多
			loadMore() {
				this.loadData();
			},
		}
	}
</script>
<style lang="scss">
	.body {
		background-color: #f2f2f2;

		.container {
			// padding: 20px;
		}

		.scroll-view {
			height: 100vh;
			/* 或者其他你需要的高度 */
			overflow: hidden;
		}

		.item {
			padding: 10px;
			border-bottom: 1px solid #eee;
		}

		.refreshing,
		.loading {
			text-align: center;
			padding: 20px;
		}

		.no-more-data {
			text-align: center;
			padding: 20px;
			color: #999;
		}

		.title {
			font-size: 36rpx;
			line-height: 76rpx;
		}

		.info {
			margin-bottom: 10px;
			background-color: #fff;
			padding: 30rpx;
			border-radius: 30rpx;
			overflow: hidden;
			position: relative;
			font-size: 36rpx;

			.state2 {
				width: 72rpx;
				height: 36rpx;
				line-height: 36rpx;
				border-radius: 6rpx;
				position: absolute;
				top: 110rpx;
				right: 35rpx;
				font-size: 24rpx;
				color: #fff;
				text-align: center;
			}

			.data {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 150rpx;
				float: left;

				text {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.data2 {
				font-size: 72rpx;
				font-weight: bold;
				line-height: 110rpx;
				text-align: center;

				text {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.fanwei {
				width: 100rpx;
				text-align: center;
				float: right;
				line-height: 36rpx;
				font-size: 36rpx;

				.danwei {
					font-size: 15.4rpx;
					color: #a0a0a0;
				}
			}

			.list {
				overflow: hidden;
				border-bottom: #f7f7f8 10rpx solid;
				padding-top: 30rpx;
				position: relative;

				.time {
					display: flex;
					line-height: 30rpx;
				}
			}

			.list:first-child {
				padding-top: 0;

				.state2 {
					top: 80rpx;
				}
			}

			.list:last-child {
				border: none;
			}
		}

		.yuan {
			height: 30rpx;
			width: 30rpx;
			border-radius: 50%;
		}

		.lv {
			background-color: #0cd10f;
			margin-right: 10rpx;
		}

		.red {
			background-color: #ff2727;
		}

		.lvcolor {
			color: #0cd10f !important;
		}

		.chengcolor {
			color: #ffa126 !important;
		}

		.zi {
			background-color: #9270ff;
			margin-right: 10rpx;
		}
	}
</style>